<!DOCTYPE html>
<html>

<head>

</head>

<body>

    <h2>JavaScript validation for empty input field</h2>
    <p>Try to submit the form without entering any text.</p>


    <xmp style="font-size: 22px; font-weight: bolder;  margin-bottom: 66px;  color: black;  font-family: '微软雅黑';">
        有 个知识点:
        1. form 表单提交时触发方法: onsubmit="return validateForm()"
        2. form 取值: var x = document.forms["myForm"]["fname"].value;

        <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
            Name: <input type="text" name="fname">
            <input type="submit" value="Submit">
        </form>
        
    </xmp>



    <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
        Name: <input type="text" name="fname">
        <input type="submit" value="Submit">
    </form>

    <script>
        function validateForm() {
            var x = document.forms["myForm"]["fname"].value;
            if (x == "" || x == null) {
                alert("Name must be filled out");
                return false;
            }
        }
    </script>

</body>

</html>